import win32com.client
import os
from datetime import datetime, timedelta
import win32print
import win32api
import shutil
import re
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('email_process.log'),
        logging.StreamHandler()
    ]
)

class OutlookEmailProcessor:
    def __init__(self):
        self.outlook = win32com.client.Dispatch("Outlook.Application")
        self.namespace = self.outlook.GetNamespace("MAPI")
        self.inbox = self.namespace.GetDefaultFolder(6)  # 6 represents the inbox folder
        self.today = datetime.now()
        self.save_dir = self._create_save_directory()

    def _create_save_directory(self):
        """创建以当前日期命名的保存目录"""
        dir_name = self.today.strftime("%Y.%m.%d")
        save_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), dir_name)
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        return save_dir

    def _is_invoice_pdf(self, filename):
        """检查��件是否为发票PDF"""
        pattern = r'\d{10}_\d{8}\.pdf'
        return bool(re.match(pattern, filename.lower()))

    def _get_invoice_number(self, filename):
        """从文件名中提取发票号"""
        if self._is_invoice_pdf(filename):
            return filename.split('.')[0]
        return None

    def process_attachments(self):
        """处理所有未读邮件的附件"""
        messages = self.inbox.Items
        messages.Sort("[ReceivedTime]", True)
        
        for message in messages:
            if message.Unread:
                logging.info(f"Processing email: {message.Subject}")
                
                # 处理附件
                if message.Attachments.Count > 0:
                    for attachment in message.Attachments:
                        self._save_and_print_attachment(attachment)
                
                # 将邮件标记为已读
                message.Unread = False
                message.Save()

    def _save_and_print_attachment(self, attachment):
        """保存并打印附件"""
        try:
            # 确定保存文件名
            original_filename = attachment.FileName
            if self._is_invoice_pdf(original_filename):
                save_filename = original_filename  # 如果是发票PDF，保持原文���名
            else:
                # 非发票PDF，使用原始文件名
                save_filename = original_filename

            save_path = os.path.join(self.save_dir, save_filename)
            
            # 保存附件
            attachment.SaveAsFile(save_path)
            logging.info(f"Saved attachment: {save_filename}")

            # 打印文件两次
            self._print_file(save_path)
            self._print_file(save_path)
            logging.info(f"Printed attachment twice: {save_filename}")

        except Exception as e:
            logging.error(f"Error processing attachment {attachment.FileName}: {str(e)}")

    def _print_file(self, filepath):
        """打印文件"""
        try:
            win32api.ShellExecute(
                0,
                "print",
                filepath,
                None,
                ".",
                0
            )
            logging.info(f"Print job sent for {filepath}")
        except Exception as e:
            logging.error(f"Error printing file {filepath}: {str(e)}")

def main():
    try:
        processor = OutlookEmailProcessor()
        processor.process_attachments()
        logging.info("Email processing completed successfully")
    except Exception as e:
        logging.error(f"Error in main process: {str(e)}")

if __name__ == "__main__":
    main() 